/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable react/prop-types */
import React, { useState, useEffect, useMemo } from 'react';
import { YunxiaoIcon } from '@alife/yunxiao-icon';
import { Select, Checkbox, Divider, Radio, Balloon, Input, Button } from '@teamix/ui';
import debounce from 'lodash.debounce';
import { navigate } from 'utils/router';
import intl from '../../../../../../locale';
import { returnNumText, returnTypeName } from '../../utils/ahooks';
import track from 'utils/track';
import utils from 'utils';
import './index.scss';

const { Option } = Select;
let searchObj;
try {
  const filter = utils.getUrlSearchParam('filter');
  searchObj = JSON.parse(filter) || {};
} catch (error) {
  searchObj = {};
}
const list = [
  { label: '代码片段', type: 'code', value: '0', active: false },
  { label: '代码库', type: 'repo', value: '0', active: false },
  { label: '提交', type: 'commit', value: '0', active: false },
  { label: '合并请求', type: 'mr', value: '0', active: false },
].map((v) => {
  if (v.type === searchObj.type) {
    v.active = true;
  }
  return v;
});
const initRadioValue = utils.getCachedData('radioValue') === 'Regular' ? 'Regular' : 'ordinary';
const initRegexpValue = searchObj.regexp || '';
const mrState = [
  {
    label: intl.get({
      id: 'code-assets.components.crListItem.EnabledFailedToMeetThe',
      defaultMessage: '已开启·未达到合并要求',
    }),
    value: 'opened',
  },
  {
    label: intl.get({
      id: 'code-assets.components.crListItem.EnabledAndCanBeMerged',
      defaultMessage: '已开启·可合并',
    }),
    value: 'accepted',
  },
  {
    label: intl.get({ id: 'code-assets.components.crListItem.Merged', defaultMessage: '已合并' }),
    value: 'merged',
  },
  {
    label: intl.get({ id: 'code-assets.components.crListItem.Disabled', defaultMessage: '已关闭' }),
    value: 'closed',
  },
];

const Search_Right = (props) => {
  const {
    grammarCountList,
    headerInputValue,
    getSearchOnChange,
    headerModeStatus,
    dslFilterCondition,
    searchType,
    setSearchType,
    searchFilterValue,
    headerSelectValue,
    setSearchLanguageValue,
    searchLanguageValue,
    searchRightMrValue,
    setMrOnchangeValue,
    getOrgMember,
    searchMrData,
    getCodeStorehouse,
    searchCodeStorehouseData,
    getCodeHouseValue,
    searchCodeHouseType,
    setRepoSelectValue,
    resetSetRepoSelectValue,
    searchVodeRepoSelectValue,
    setRowColSpanRight,
    rowSpanCol: { rightOpen },
    leftDataNum,
  } = props;
  const formatValue = utils.getUrlParam({ name: 'inputtext', type: 'search' });
  const [listState, setListState] = useState(list);
  const [radioValue, setRadioValue] = useState(initRadioValue);
  const [regexpValue, setRegexpValue] = useState(initRegexpValue);
  const findArrayTypeValue = (type) => {
    if (!searchFilterValue || (searchFilterValue && searchFilterValue.length === 0)) return 0;
    const value = searchFilterValue.filter((va) => va.type === type);
    return value.length > 0 ? value[0] : 0;
  };
  useEffect(() => {
    if (utils.getCachedData('search-filter-open')) {
      searchVodeRepoSelectValue.visibility =
        utils.getCachedData('search-filter-open') === '0' ? '私有' : '企业可见';
    }
    if (utils.getCachedData('creatorValueId')) {
      searchVodeRepoSelectValue.creatorId =
        searchMrData &&
        searchMrData.find((item) => item._userId === utils.getCachedData('creatorValueId'))
          ?._userId;
    }

    const lists = listState.map((va) => {
      const value = findArrayTypeValue(va.type);
      if (va.type === searchType) {
        return { ...va, active: true, value: value === 0 ? value : value.fiterCount.totoalCount };
      } else {
        return { ...va, active: false, value: value === 0 ? value : value.fiterCount.totoalCount };
      }
    });
    setListState(lists);
  }, [searchType, headerSelectValue, searchFilterValue]);
  const languageList = useMemo(() => {
    const value = findArrayTypeValue(searchType);
    return value.languageCount;
  }, [searchType, headerSelectValue, searchFilterValue]);
  useEffect(() => {
    getOrgMember();
    getCodeStorehouse();
  }, []);
  const setMrValue = (value, type) => {
    setMrOnchangeValue({ ...searchRightMrValue, [type]: value }, type);
  };
  const mrSelectOptionhander = () => {
    return searchMrData.map((va) => {
      return (
        <Option value={va._userId} key={va._userId}>
          {va.name}
        </Option>
      );
    });
  };
  const getCodeRegexp = debounce((v) => {
    props.getCodeStorehouse(v);
  }, 500);
  const checkboxChange = (checked) => {
    track({
      action: checked ? 'apply_mine_repo_filter' : 'cancel_mine_repo_filter',
      page: 'Search-Page',
      type: returnTypeName(searchType),
      // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
      control: returnNumText(leftDataNum),
      // default:还没有搜索，none:当前搜索结果=0，less:0<当前搜索结果<=10，middle:10<当前搜索结果<=100，large:当前搜索结果 > 100
    });
    const filter = utils.getUrlSearchParam('filter') || '{}';

    const filterObj = JSON.parse(filter);
    filterObj.isMine = checked;
    const filterStr = JSON.stringify(filterObj);
    const inputtext = utils.getUrlSearchParam('inputtext');
    const searchcodestorehousedata = utils.getUrlSearchParam('searchcodestorehousedata') || '';
    navigate(
      `/search?inputtext=${encodeURIComponent(
        inputtext,
      )}&searchcodestorehousedata=${encodeURIComponent(
        searchcodestorehousedata,
      )}&filter=${encodeURIComponent(filterStr)}`,
    );

    props.headerSelectOnChange(checked ? 'mine' : 'all');
  };
  const regexpEnter = () => {
    track({
      action: 'select_repo_filter',
      page: 'Search-Page',
      type: 'regex',
      control: '',
    });
    track({
      action: 'apply_regex_repo_filter',
      page: 'Search-Page',
      type: returnTypeName(searchType),
      control: returnNumText(leftDataNum),
    });
    const filter = utils.getUrlSearchParam('filter') || '{}';

    const filterObj = JSON.parse(filter);
    filterObj.regexp = regexpValue;
    const filterStr = JSON.stringify(filterObj);
    const inputtext = utils.getUrlSearchParam('inputtext');
    navigate(
      `/search?inputtext=${encodeURIComponent(
        inputtext,
      )}&searchcodestorehousedata=&filter=${encodeURIComponent(filterStr)}`,
    );

    getCodeHouseValue({ isRegexp: true, value: regexpValue, name: regexpValue });
  };
  const setRepoValue = (value, type) => {
    setRepoSelectValue({ ...searchVodeRepoSelectValue, [type]: value });
  };
  const listType = (va) => {
    switch (true) {
      case va.type === 'code':
        return 'code_snippet';
      case va.type === 'repo':
        return 'repo';
      case va.type === 'commit':
        return 'code_commit';
      default:
        return 'code_mr';
    }
  };
  const renderCodeBase = () => {
    return (
      <div className="search_right_language">
        <div className="search_right_language_title">
          <span>代码库</span>
        </div>
        <Checkbox
          checked={headerSelectValue === 'mine'}
          onChange={checkboxChange}
          style={{ padding: '0 9px' }}
        >
          我参与的库
        </Checkbox>
        <Divider style={{ marginLeft: 9, marginRight: 9, minWidth: 'auto', width: 'auto' }} />
        <Radio.Group
          onChange={(v) => {
            getCodeHouseValue({}, v === 'Regular');
            setRadioValue(v);
            utils.setCachedData('radioValue', v);
            setRegexpValue('');
            if (v === 'ordinary') {
              track({
                action: 'click_normal_repo_filter',
                page: 'Search-Page',
                type: returnTypeName(searchType),
                // 右边选中的筛选类型，代码片段:code_snippet，代码库:code_repo，提交:code_commit，合并请求:code_mr
                control: returnNumText(leftDataNum),
                // default:还没有搜索，none:当前搜索结果=0，less:0<当前搜索结果<=10，
                // middle:10<当前搜索结果<=100，large:当前搜索结果 > 100
              });
            } else if (v === 'Regular') {
              track({
                action: 'click_regex_repo_filter',
                page: 'Search-Page',
                type: 'regex',
                control: returnNumText(leftDataNum),
              });
            }
          }}
          value={radioValue}
          itemDirection="hoz"
          className="codeup_search_radio_select"
        >
          <Radio id="ordinary" value="ordinary">
            常规筛选
          </Radio>
          <Radio id="Regular" value="Regular">
            正则匹配
            <Balloon.Tooltip
              trigger={
                <YunxiaoIcon
                  type="question-line"
                  className="build-summary-whitelist-icon"
                  size="small"
                  style={{ marginLeft: 3, color: 'var(--color-fill1-6, #8b8b8b)' }}
                />
              }
              align="tl"
            >
              支持库路径正则筛选，如 groupA/.*
            </Balloon.Tooltip>
          </Radio>
        </Radio.Group>
        {radioValue === 'ordinary' ? (
          <Select
            aria-label="请选择"
            style={{ width: '100%', padding: '0 9px' }}
            showSearch
            mode="multiple"
            value={searchCodeHouseType.value}
            onChange={(v, _type, item) => {
              track({
                action: 'select_repo_filter',
                page: 'Search-Page',
                type: 'conventional',
                control: '',
              });
              track({
                action: 'apply_normal_repo_filter',
                page: 'Search-Page',
                type: returnTypeName(searchType),
                control: returnNumText(leftDataNum),
              });
              const inputtext = utils.getUrlSearchParam('inputtext');
              const filter = utils.getUrlSearchParam('filter') || '';
              try {
                if (v && v.length) {
                  navigate(
                    `${window.location.origin}${
                      window.location.pathname
                    }?inputtext=${encodeURIComponent(
                      inputtext,
                    )}&searchcodestorehousedata=${encodeURIComponent(
                      JSON.stringify(v),
                    )}&filter=${encodeURIComponent(filter)}`,
                  );
                } else {
                  navigate(
                    `${window.location.origin}${
                      window.location.pathname
                    }?inputtext=${encodeURIComponent(inputtext)}&filter=${encodeURIComponent(
                      filter,
                    )}`,
                  );
                }
              } catch (err) {
                // eslint-disable-next-line no-console
                console.log(err);
              }
              getCodeHouseValue(
                v && v.length === 0
                  ? {}
                  : {
                      isRegexp: false,
                      value: v && v.length === 0 ? '' : v,
                      name: item || [],
                    },
              );
              getCodeRegexp('');
            }}
            onSearch={getCodeRegexp}
          >
            {searchCodeStorehouseData.length > 0 &&
              searchCodeStorehouseData.map((va) => {
                return (
                  <Option
                    value={
                      va.id === 'codeup_search_regular_expression'
                        ? va.value
                        : va.path_with_namespace
                    }
                    key={va.path_with_namespace}
                  >
                    {va.name}
                  </Option>
                );
              })}
          </Select>
        ) : (
          <div style={{ padding: '0 9px' }}>
            <Input
              style={{ width: '100%' }}
              placeholder="请输入库路径正则"
              value={regexpValue}
              onChange={(v) => setRegexpValue(v)}
              onPressEnter={regexpEnter}
            />
          </div>
        )}
      </div>
    );
  };
  const SyntaxFiltering = () => {
    return (
      <div className="search_right_language">
        <div className="search_right_language_title">
          <span style={{ lineHeight: '40px' }}>语法过滤</span>
          <Balloon.Tooltip
            popupStyle={{ marginTop: '0' }}
            align="rt"
            alignEdge
            trigger={
              <a href="https://help.aliyun.com/document_detail/419325.html" target="_blank" rel="noreferrer">
                <Button text style={{ marginTop: '-3px' }}>
                  <YunxiaoIcon type="question-line" className="help-icon" />
                </Button>
              </a>
            }
            closable={false}
          >
            帮助
          </Balloon.Tooltip>
        </div>
        <div>
          {dslFilterCondition &&
            dslFilterCondition.map((item) => (
              <div
                key={item.reservedKey}
                className={item.active ? 'active' : null}
                onClick={() => {
                  if (headerInputValue.trim() === '') {
                    getSearchOnChange(item.reservedKey);
                    props?.editorFocusObj?.trigger('keyboard', 'type', { text: item.reservedKey });
                    props?.editorFocusObj?.focus();
                  } else {
                    getSearchOnChange(`${headerInputValue.trimEnd() } ${ item.reservedKey}`);
                    props?.editorFocusObj?.trigger('keyboard', 'type', {
                      text: ` ${ item.reservedKey}`,
                    });
                    props?.editorFocusObj?.focus();
                  }
                }}
              >
                {syntaxFilteringHander(item)}
              </div>
            ))}
        </div>
      </div>
    );
  };
  const syntaxFilteringHander = (item) => {
    return (
      <div className="syntax_filtering">
        <span className="syntax_filtering_reserved_key">{item.reservedKey}</span>
        <span className="syntax_filtering_meaning">{item.meaning}</span>
      </div>
    );
  };
  const isSelectionEmpty = () => {
    return (
      radioValue === 'ordinary' &&
      regexpValue === '' &&
      searchType === 'code' &&
      (Object.keys(searchCodeHouseType).length === 0 ||
        (searchCodeHouseType.value.length === 0 && searchCodeHouseType.isRegexp === false)) &&
      headerSelectValue === 'all'
    );
  };
  return (
    <>
      <section className={`codeup_search_right ${rightOpen ? 'codeup_search_right_icon' : null}`}>
        <div className="search_right_fiter_title">
          <span style={{ lineHeight: '40px' }}>筛选</span>
          {headerModeStatus === 'ordinary' && !isSelectionEmpty() && (
            <span
              onClick={() => {
                setRadioValue('ordinary');
                setRegexpValue('');
                setSearchType('code');
                props.getCodeHouseValue({ value: [], isRegexp: false }, true);
                props.headerSelectOnChange('all');
                const inputtext = utils.getUrlSearchParam('inputtext');
                navigate(
                  `/search?inputtext=${encodeURIComponent(inputtext)}&searchcodestorehousedata=`,
                );
              }}
            >
              清空筛选
            </span>
          )}
        </div>
        <div className="search_right_list">
          {listState &&
            listState.length > 0 &&
            listState.map((va, index) => {
              if (headerModeStatus === 'grammar') {
                va.value = grammarCountList[index]?.totoalCount;
              }
              return (
                <div
                  className={`search_right_list_item ${va.active ? 'active' : null}`}
                  key={va.label}
                  onClick={() => {
                    track({
                      action: 'select_object_type',
                      page: 'Search-Page',
                      type: listType(va),
                      control: '',
                    });
                    const filter = utils.getUrlSearchParam('filter') || '{}';

                    const filterObj = JSON.parse(filter);
                    filterObj.type = va.type;
                    const filterStr = JSON.stringify(filterObj);
                    const inputtext = utils.getUrlSearchParam('inputtext');
                    const searchcodestorehousedata =
                      utils.getUrlSearchParam('searchcodestorehousedata') || '';
                    navigate(
                      `/search?inputtext=${encodeURIComponent(
                        inputtext,
                      )}&searchcodestorehousedata=${encodeURIComponent(
                        searchcodestorehousedata,
                      )}&filter=${encodeURIComponent(filterStr)}&is_dsl=${
                        headerModeStatus === 'grammar'
                      }`,
                    );

                    if (va.type !== 'code' && searchLanguageValue) {
                      setSearchLanguageValue('', true);
                      setSearchType(va.type);
                    } else if (
                      va.type !== 'repo' ||
                      searchVodeRepoSelectValue.creatorId ||
                      searchVodeRepoSelectValue.visibility
                    ) {
                      resetSetRepoSelectValue({ creatorId: '', visibility: '' });
                      setSearchType(va.type);
                    } else {
                      setSearchType(va.type);
                    }
                  }}
                >
                  <span>{va.label}</span>
                  <span>{formatValue ? va.value : 0}</span>
                </div>
              );
            })}
        </div>
        {headerModeStatus === 'ordinary' &&
          searchType === 'code' &&
          languageList &&
          languageList.length > 0 && (
            <div className="search_right_language">
              <div className="search_right_language_title">
                <span>编程语言</span>
                {searchLanguageValue ? (
                  <span onClick={() => setSearchLanguageValue('')}>取消</span>
                ) : (
                  ''
                )}
              </div>
              {languageList &&
                languageList.map((va) => {
                  const keys = Object.keys(va);
                  const values = Object.values(va);
                  return (
                    <div
                      className={`search_right_language_item ${
                        searchLanguageValue === keys[0] ? 'active' : null
                      }`}
                      key={keys[0]}
                      onClick={() => {
                        track({
                          action: 'select_language_type',
                          page: 'Search-Page',
                          type: `${keys}`,
                          control: '',
                        });
                        setSearchLanguageValue(...keys, false, values[0]);
                      }}
                    >
                      <span>{keys}</span>
                      {searchLanguageValue === keys[0] ? (
                        <YunxiaoIcon type="true-line" style={{ color: '#1B9AEE' }} />
                      ) : (
                        <span>{va[keys]}</span>
                      )}
                    </div>
                  );
                })}
            </div>
          )}
        {headerModeStatus === 'ordinary' ? renderCodeBase() : SyntaxFiltering()}

        {headerModeStatus === 'ordinary' && searchType === 'repo' && (
          <div className="search_right_select">
            <div className="search_right_select_list">
              <label>创建人</label>
              <Select
                showSearch
                aria-label="请选择"
                style={{ width: '100%' }}
                popupStyle={{ width: 202 }}
                hasClear
                value={searchVodeRepoSelectValue.creatorId}
                onChange={(value) => {
                  setRepoValue(value, 'creatorId');
                  utils.setCachedData('creatorValueId', value);
                }}
              >
                {mrSelectOptionhander()}
              </Select>
            </div>
            <div className="search_right_select_list">
              <label>公开性</label>
              <Select
                aria-label="请选择"
                style={{ width: '100%' }}
                hasClear
                value={searchVodeRepoSelectValue.visibility}
                onChange={(value) => {
                  setRepoValue(value, 'visibility');
                  utils.setCachedData('search-filter-open', String(value));
                }}
              >
                <Option value="0">私有</Option>
                {/* <Option value="10">登录才能查看</Option> */}
                <Option value="10">企业可见</Option>
              </Select>
            </div>
          </div>
        )}
        {headerModeStatus === 'ordinary' && searchType === 'mr' && (
          <div className="search_right_select">
            <div className="search_right_select_list">
              <label>创建人</label>
              <Select
                showSearch
                aria-label="请选择"
                style={{ width: '100%' }}
                popupStyle={{ width: 202 }}
                hasClear
                value={searchRightMrValue.establish}
                onChange={(value) => setMrValue(value, 'establish')}
              >
                {mrSelectOptionhander()}
              </Select>
            </div>
            <div className="search_right_select_list">
              <label>评审人</label>
              <Select
                showSearch
                aria-label="请选择"
                style={{ width: '100%' }}
                popupStyle={{ width: 202 }}
                hasClear
                value={searchRightMrValue.review}
                onChange={(value) => setMrValue(value, 'review')}
              >
                {mrSelectOptionhander()}
              </Select>
            </div>
            <div className="search_right_select_list">
              <label>评审状态</label>
              <Select
                aria-label="请选择"
                style={{ width: '100%' }}
                hasClear
                value={searchRightMrValue.state}
                onChange={(value) => setMrValue(value, 'state')}
              >
                {mrState.map((va) => {
                  return (
                    <Option value={va.value} key={va.value}>
                      {va.label}
                    </Option>
                  );
                })}
              </Select>
            </div>
          </div>
        )}
      </section>
      {rightOpen && (
        <div className="codeup_search_right_icon_button">
          <Button
            text
            onClick={() => {
              setRowColSpanRight(rightOpen);
            }}
          >
            <YunxiaoIcon
              type={!rightOpen ? 'arrow-left-2-line' : 'arrow-right-2-line'}
              style={{
                border: '1px solid #e8e8e8',
                borderRadius: '50%',
                backgroundColor: 'rgb(139, 139, 139)',
                color: '#fff',
              }}
            />
          </Button>
        </div>
      )}
    </>
  );
};

export default Search_Right;
